﻿using _8Group.MES.IService;
using _8Group.MES.MeasuringUnit;
using _8Group.MES.MeasuringUnit.DTO;
using _8Group.MES.MengIService.DTO;
using _8Group.MES.Model.MD主数据;
using FourGroups.Project;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;

namespace _8Group.MES.Service
{
    [ApiExplorerSettings(GroupName = "孟祥宇")]
    /// <summary>
    /// 物料产品管理服务实现
    /// </summary>
    public class MaterialProductService:ApplicationService,IMaterialProductService
    {
        /// <summary>
        /// 物料产品表
        /// </summary>
        private readonly IRepository<MdItem, int> _mdItemRepository;
        public MaterialProductService(IRepository<MdItem, int> mdItemRepository)
        {
            _mdItemRepository = mdItemRepository;
        }
        /// <summary>
        /// 获取物料产品列表
        /// </summary>
        /// <returns></returns>
        public async Task<string> GetMdItemsListAsync(string ?code,string? name,int page,int limit)
        {
            var mditem = await _mdItemRepository.GetQueryableAsync();

            mditem= mditem.WhereIf(!string.IsNullOrEmpty(code), x => x.ItemCode.Contains(code));
            mditem= mditem.WhereIf(!string.IsNullOrEmpty(name), x => x.ItemName.Contains(name));

            int listCount=mditem.Count();
            mditem= mditem.OrderBy(x => x.Id).Skip((page - 1) * limit).Take(limit);

            return JsonConvert.SerializeObject(new {code="0",data= mditem.ToList(),count= listCount, msg="获取物料产品列表成功"}, Formatting.Indented);
        }
        /// <summary>
        /// 物料产品添加
        /// </summary>
        /// <param name="mdItem"></param>
        /// <returns></returns>
        public async Task<int> AddMdItemAsync(MdItemDTO mdItem)
        {
            var n = AutoMapperExt.MapTo<MdItem>(mdItem);
            await _mdItemRepository.InsertAsync(n);
            return 1;
        }
        /// <summary>
        /// 物料产品修改
        /// </summary>
        /// <param name="mdItem"></param>
        /// <returns></returns>
        public async Task<int> UpdateMdItemAsync(UpdateMdItemDTO mdItem)
        {
            mdItem.UpdateBy = "孟祥宇";
            mdItem.UpdateTime = DateTime.Now;
            var model = AutoMapperExt.MapTo<MdItem>(mdItem);
            await _mdItemRepository.UpdateAsync(model);
            return 1;

        }
        /// <summary>
        /// 物料产品删除
        /// </summary>
        /// <param name="mdItem"></param>
        /// <returns></returns>
        public async Task<int> DeleteMdItemAsync(int id)
        {
            await _mdItemRepository.DeleteAsync(id,true);
            return 1;
        }
    }
}
